<template lang="pug">
  el-amap(
    vid="amap"
    :zoom="zoom"
    :center="mapCenter"
    :style="amapStyle"
    v-loading="loading"
    :element-loading-text="message"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 0.9)")
    div(
      v-for="(data, d) in dataList"
      :key="d")
      div(
        v-for="(markerItem, i) in data"
        :key="i")
        div(
          v-for="(marker, j) in markerItem"
          :key="j")
          el-amap-marker(
            v-if="marker.showMarker"
            v-bind="marker"
            :title="marker.title"
            :position="marker.position"
            :events="marker.events"
            :visible="marker.visible"
            :draggable="marker.draggable")
        el-amap-polyline(
          :path="markerItem | polylinePath"
          :strokeColor="markerItem[0].strokeColor")
    el-amap-info-window(
      v-if="isShowMessage"
      ref="windowsPage"
      :isCustom="true"
      :position="windowsPage.position"
      :content="windowsPage.content"
      :visible="windowsPage.visible"
      :offset="windowsPage.offset"
      :showShadow="true"
      :events="windowsPage.events"
      :closeWhenClickMap="true")
</template>

<script>
/**
 * @name mapsPage 组件
 * @author 黄丰瑞 <huangfr@gddit.com>
 * @description 通过与后台预定的接口格式以及可配置地图资源数组定义直接出地图
 *
 * @update 增加起始点
 * @description 特定的接口格式 如：抄表记录>抄表轨迹
 * @author 林墁霓
 *
 * @update 支持relation、时间格式化修复
 * @author 温泽荣
 */
import { groupBy } from 'lodash'
import destination from '@/assets/img/destination.png'
import origin from '@/assets/img/origin.png'
// import { infoRender } from '@/components/infoRender/infoRender'

export default {
  name: 'mapsPage',
  props: {
    center: { // 地图中心点（必填）
      type: Array,
      default () {
        return this.$config.lonlat
      }
    },
    zoom: { // 地图缩放级别（必填）
      type: Number,
      default: 14
    },
    markers: { // 标点配置（必填）
      type: Object,
      default: () => ({})
    },
    resource: { // 接口名（必填）
      type: String,
      default: null
    },
    columns: { // 字段配置
      type: Object,
      default: () => ({})
    },
    relation: { // relation
      type: Object,
      default: () => ({})
    },
    height: {
      type: Number,
      default: 500
    }
  },
  filters: {
    polylinePath (path) {
      const pathList = path.map(item => {
        return item.position
      })
      return pathList
    }
  },
  data () {
    return {
      mapCenter: this.center,
      isShowMessage: false,
      colorList: ['#FA5555', '#409EFF', '#EB9E05', '#67C23A'],
      isData: false,
      windowsPage: {},
      dataList: [],
      relationList: [],
      loading: true,
      message: '加载中...',
      lastMark: 0 // 最后的坐标点位置
    }
  },
  mounted () {
    this.getRelation()
    // console.log(this.columns)
  },
  computed: {
    amapStyle () {
      return {
        height: this.height + 'px',
        width: '100%'
      }
    }
  },
  methods: {
    getRelation () {
      this.message = '正在加载地图模块...'
      const columnsList = this.columns
      const relation = Object.keys(columnsList).filter(key => columnsList[key].relation).map(key => columnsList[key].relation)
      this.$getRelation({
        relations: relation.join(',')
      }).then(data => {
        this.relationList = data
        this.getData()
        // Object.keys(this.columns).map(key => {
        //   const relation = this.columns[key].relation
        //   if (data[relation]) {
        //     this.columns[key].options = [...this.columns[key].optionsInit || [], ...data[relation]].map(option => {
        //       console.log(this.columns[key])
        //       this.$set(this.columns[key], 'value', this.columns[key].value)
        //     })
        //   }
        // })
      })
    },
    getData () {
      this.$get({
        url: this.resource
      }).then(data => {
        this.isData = true
        if (data) {
          this.getMaters(data)
        }
      })
    },
    getInfoData (data, infoList) {
      return infoList.length ? infoList.map(info => {
        let infoValue = data[info]
        if (this.columns[info].render) {
          infoValue = this.columns[info].render.type === 'time' ? this.$moment(data[info]).format('YYYY-MM-DD HH:mm:ss') : data[info]
        }
        return {
          label: this.columns[info].label,
          relation: this.columns[info].relation,
          value: infoValue
        }
      }) : []
    },
    getMaters (data) {
      const filterData = data.map(item => {
        return item.data.filter(mark => mark.lonlat.length)
      })
      this.mapCenter = filterData[0].length ? filterData[0][filterData[0].length - 1].lonlat : this.$config.lonlat
      // 抄表员数组
      const dataLength = filterData.length
      this.lastMark = filterData.length
      this.dataList = filterData.map((item, tIndex) => {
        // 点类型数组
        const markersTypeList = groupBy(item, 'type')
        return Object.keys(markersTypeList).map((key, index) => {
          const markerConfig = this.markers[key]
          // 排序 跟 筛选掉
          const lonlatList = markersTypeList[key].filter(item => item.lonlat.length !== 0).sort((a, b) => {
            return a.createTime - b.createTime
          })
          // console.info('lonlatList--', lonlatList.length)
          return lonlatList.map((markItem, j) => {
            const infoList = this.getInfoData(markItem.data, markerConfig.infoList)
            const {markIcon, zIndex} = this.renderMarkIcon(dataLength, j, tIndex)
            return {
              icon: markIcon,
              showMarker: markerConfig.showMarker,
              strokeColor: this.colorList[index],
              position: markItem.lonlat,
              zIndex: zIndex,
              events: {
                click: (a) => {
                  const _this = this
                  this.isShowMessage = true
                  this.windowsPage = {
                    position: markItem.lonlat,
                    content: `<div
                      style="max-width:400px;
                      border:1px solid #ddd;
                      padding:10px;
                      background:rgba(0,0,0,0.5);
                      color: #fff;">
                    ${this.showInfoData(infoList)}
                    </div>`,
                    offset: [90, -20],
                    visible: true,
                    events: {
                      close () {
                        _this.isShowMessage = false
                      }
                    }
                  }
                }
              },
              title: item.name,
              visible: true
            }
          })
        })
      })
      this.loading = false
    },
    renderMarkIcon (total, index, tIndex) {
      const _index = tIndex || index
      // console.info('this.lastMark:', this.lastMark)
      return {
        markIcon: _index === 0 ? origin : (_index === total - 1 ? destination : this.$config.mapIcon),
        zIndex: _index === 0 || _index === total - 1 ? 120 : 100
      }
    },
    showInfoData (infoList) {
      let data = ''
      infoList.forEach((info, key) => {
        let infoValue = ''
        if (info.relation !== undefined && this.relationList[info.relation] !== undefined) {
          // console.log(this.relationList[info.relation])
          this.relationList[info.relation].forEach(item => {
            if (info.value !== undefined && item.value === info.value) {
              infoValue = item.label
            }
          })
        }
        data += `<p style="margin: 0">${info.label}：${infoValue || info.value || ''}</p>`
        // data += `<p style="margin: 0">${info.label}：${info.value}</p>`
      })
      return data
    }
  }
}
</script>
<style scoped lang="sass">
.amap-demo
  height: 450px
</style>
